#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import sys

from flask import render_template, request, jsonify
from app import commom, PAGE_NUM, page_code, upload_files
from app.util import admin_login
from dbConnection.MysqlConn import Mysql
from . import admin

reload(sys)
sys.setdefaultencoding('utf8')


# 课程列表
@admin.route('/admin/course_list.html')
@admin_login
def course_list():
    tc = commom.get_teacher()
    zt = commom.get_subject()
    td = commom.get_type()
    return render_template('admin/course/course_list.html', tc=tc, zt=zt, td=td)


# 获取数据
@admin.route('/admin/course_list_post', methods=['post'])
@admin_login
def course_list_post():
    parms = ['cname', 'status', 'uid', 'tid', 'sid']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', '1')
    c_num = (int(p) - 1) * PAGE_NUM
    sql = "select c.courseName, c.cover, c.status, c.addTime, c.clickNum, h.nickName, t.courseName AS tname, t.tid, c.cid, c.uid FROM " \
          "girl_course AS c LEFT JOIN girl_type AS t ON t.tid = c.tid LEFT JOIN girl_teacher AS h ON h.uid = c.uid WHERE 1=1"
    sql2 = "select count(t.uid) AS con FROM girl_course AS c LEFT JOIN girl_type AS t ON t.tid = c.tid LEFT JOIN " \
           "girl_teacher AS h ON h.uid = c.uid WHERE 1=1"
    if maps['cname']:
        sql += " and c.cid = '" + maps['cname'] + "' or locate('" + maps['cname'] + "', c.courseName)>0"
        sql2 += " and c.cid = '" + maps['cname'] + "' or locate('" + maps['cname'] + "', c.courseName)>0"
    if maps['status']:
        sql += " and c.status = '%s'" % maps['status']
        sql2 += " and c.status = '%s'" % maps['status']
    if maps['uid']:
        sql += " and c.uid = '%s'" % maps['uid']
        sql2 += " and c.uid = '%s'" % maps['uid']
    if maps['sid']:
        sql += " and c.sid = '%s'" % maps['sid']
        sql2 += " and c.sid = '%s'" % maps['sid']
    if maps['tid']:
        sql += " and c.tid = '%s'" % maps['tid']
        sql2 += " and c.tid = '%s'" % maps['tid']
    sql += " order by c.cid desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    if cont:
        pages = math.ceil(cont['con'] / float(PAGE_NUM))
    else:
        pages = 0
    pages = int(pages)
    route_path = 'get_data'
    if pages > 0:
        html_str = page_code.page_code_html_post(int(p), route_path, pages)
    else:
        html_str = ''
    if res:
        for d in res:
            d['addTime'] = str(d['addTime'])
            if d['cover'] and d['cover'].startswith('http') is False:
                d['cover'] = upload_files.baseUrl + d['cover']
        data = {
            'status':1,
            'res':res,
            'page':html_str,
            'p':p
        }
    else:
        data = {
            'status':2,
            'page':html_str
        }
    return jsonify(data)


# 获取对应的分类
@admin.route('/admin/get_types_post', methods=['post'])
@admin_login
def get_types_post():
    sid = request.values.get('sid')
    sql = "select courseName, tid FROM girl_type WHERE 1=1"
    if sid:
        sql += " and sid = '%s'" % sid
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    if res:
        data = {
            'status':1,
            'res':res
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 课程操作
@admin.route('/admin/update_course_post', methods=['post'])
@admin_login
def update_course_post():
    cid = request.values.get('cid')
    pid = request.values.get('pid')
    if pid == '1':
        sql = "update girl_course set status = 1 WHERE cid = '%s'" % cid
    elif pid == '2':
        sql = "update girl_course set status = 0 WHERE cid = '%s'" % cid
    elif pid == '3':
        sql = "delete FROM girl_course WHERE cid = '%s'" % cid
    else:
        return jsonify({'status':0})
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 新增课程
@admin.route('/admin/course_add.html')
@admin_login
def course_add():
    sj = commom.get_subject()
    type_list = commom.get_type()
    tc = commom.get_teacher()
    return render_template('admin/course/course_add.html', sj=sj, type_list=type_list, tc=tc)


# 获取科目对应的课程
@admin.route('/admin/subject_detail', methods=['post'])
@admin_login
def subject_detail():
    sid = request.values.get('sid')
    sql = "select tid, courseName FROM girl_type WHERE sid = '%s' AND status  = 1" % sid
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    if res:
        data = {
            'status':1,
            'res':res
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 新增课程处理
@admin.route('/admin/course_add_post', methods=['post'])
@admin_login
def course_add_post():
    tc = request.values.get('tc')
    km = request.values.get('km')
    cname = request.values.get('cname')
    info = request.values.get('info')
    ctype = request.values.get('ctype')
    file_img = request.files.get('file')
    res = insert_new_course(ctype, cname, tc, info, km)
    if res > 0:
        img_url = upload_files.course_img(file_img, ctype, 'img', res)
        if img_url:
            update_course_img(res, img_url)
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 编辑课程
@admin.route('/admin/course_detail.html')
@admin_login
def course_detail():
    cid = request.values.get('cid')
    sql = "select t.courseName as tname, c.cid, c.tid, c.courseName as cname, h.nickName as hname, c.info, d.typeName, " \
          "c.cover FROM girl_course AS c LEFT JOIN girl_type AS t ON t.tid = c.tid LEFT JOIN girl_teacher AS h " \
          "ON h.uid = c.uid LEFT JOIN girl_subject AS d ON d.sid = c.sid WHERE c.cid = '%s'" % cid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    if res:
        if res['cover'] and res['cover'].startswith('http') is False:
            res['cover'] = upload_files.baseUrl + res['cover']
    return render_template('admin/course/course_detail.html', res=res)


# 编辑课程处理
@admin.route('/admin/course_detail_post', methods=['post'])
@admin_login
def course_detail_post():
    cname = request.values.get('cname')
    info = request.values.get('info')
    file_img = request.files.get('file')
    cid = request.values.get('cid')
    res = get_course_detail(cid)
    if res is None:
        return jsonify({'status':0})
    img_url = upload_files.course_img(file_img, res['tid'], 'img', res['cid'])
    sql = "update girl_course SET courseName = '%s', info = '%s'" % (cname, info)
    if img_url:
        sql += ", cover = '%s'" % img_url
    sql += " where cid = '%s'" % cid
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':2
        }
    return jsonify(data)


# 插入新课程
def insert_new_course(tid, cname, uid, info, sid):
    sql = "insert INTO girl_course(tid, courseName, info, uid, sid, addTime) VALUES ('%s', '%s', '%s', '%s', '%s'," \
          " now())" % (tid, cname, info, uid, sid)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 更新课程封面
def update_course_img(cid, url):
    sql = "update girl_course SET cover = '%s' WHERE cid = '%s'" % (url, cid)
    mysql = Mysql()
    mysql.update(sql, None)
    mysql.dispose()


# 获取课程详情
def get_course_detail(cid):
    sql = "select * FROM girl_course WHERE cid = '%s'" % cid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res